import { useMemoizedFn } from 'ahooks';
import { Cartesian3, ImageryLayer, UrlTemplateImageryProvider } from 'cesium';
import { isNil } from 'lodash';
import { useEffect } from 'react';
import { useCesium } from 'resium';
import { useAppSelector } from '../../../../store';

export default function Demo() {
    const { viewer } = useCesium();
    const pos = useAppSelector((state) => state.scene.initPosition);

    const clearImageryLayers = useMemoizedFn(() => {
        if (isNil(viewer)) return;
        if (viewer.imageryLayers.get(0)) {
            viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
            clearImageryLayers();
        } else {
            return;
        }
    });

    useEffect(() => {
        if (isNil(viewer)) return;
        clearImageryLayers();

        const key = 'ceb09f2b2303a8e4becb4e9f0c94967b';
        const url = `http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${key}`;
        const layer = new ImageryLayer(
            new UrlTemplateImageryProvider({
                url,
            })
        );
        viewer.imageryLayers.add(layer);

        const urlText = `https://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${key}`;
        const layerText = new ImageryLayer(
            new UrlTemplateImageryProvider({
                url: urlText,
            })
        );
        viewer.imageryLayers.add(layerText);

        const target = Cartesian3.fromDegrees(pos.longitude, pos.latitude, 10000000);
        viewer.camera.setView({
            destination: target,
        });
    }, [clearImageryLayers, pos, viewer]);

    return null;
}
